//
//  Hear_PreviewViewController.m
//  Hear
//
//  Created by mac on 2018/4/29.
//  Copyright © 2018年 mac. All rights reserved.
//

#import "Hear_PreviewViewController.h"

#import "Hear_PhonographView.h"

#import "Hear_TopicShowModel.h"

#import "OSSImageUploader.h"

#import "HRGetUserinfoViewModel.h" // 个人信息
#import "HRUpdataUserInfoModel.h" // 个人数据模型


@interface Hear_PreviewViewController ()

/** 播放器 */
@property (nonatomic, strong) AVAudioPlayer *player;

/** 背景图 */
@property (nonatomic, strong) Hear_PhonographView *bgview;

@property (nonatomic, strong) HRGetUserinfoViewModel *getUserInfoModel;

@property (nonatomic, strong) HRUpdataUserInfoModel *infomodel;

@property (nonatomic, strong) UIButton *sendbtn;

@end

static BOOL isRotate = YES;

@implementation Hear_PreviewViewController

- (HRGetUserinfoViewModel *)getUserInfoModel{
    if (_getUserInfoModel == nil){
        _getUserInfoModel = [HRGetUserinfoViewModel new];
    }
    return _getUserInfoModel;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.translucent = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self registerNoti];
}

- (void)registerNoti {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographPlayAction:) name:@"Hear_PhonographPlay" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(Hear_PhonographRotatingImgAction:) name:@"Hear_PhonographRotatingImg" object:nil];
}

- (void)setupUI {
    self.title = @"预览";
    
    UIButton *sendbtn = [[UIButton alloc]init];
    sendbtn.size = CGSizeMake(30, 25);
    [sendbtn setTitle:@"发布" forState:UIControlStateNormal];
    sendbtn.titleLabel.font = CustomUIFont(14);
    [sendbtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [sendbtn addTarget:self action:@selector(sendbtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.sendbtn = sendbtn;
    UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:sendbtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    CGFloat height = ScreenHeight - kTopHeight;
    
    Hear_PhonographView *view = [[Hear_PhonographView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, height)];
    view.enble = @"1";
    self.bgview = view;
    [self.view addSubview:view];
    
    [self getUserInfo];
}

#pragma mark 加载预览
- (void)getUserInfo{
    
    WeakSelf
    [self.getUserInfoModel getUserInfoRequestModel:@{@"CurrentUserLocalId":USERID,@"VisitedUserLocalId":USERID} isSeccess:^(HRUpdataUserInfoModel *infModel) {
        weakSelf.infomodel = infModel;
        
        [weakSelf loadData];
    }];
    
}

- (void)loadData {
    self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:self.soundStr] error:nil];
    
    [self.player play];
    
    [self.bgview.rotatingImg resumeRotate];
    
    if (self.topicname.length) {
        self.bgview.titleLB.text = self.topicname;
        [self.bgview.header sd_setImageWithURL:GetUrlWithStr(self.infomodel.UserPictureName)];
        self.bgview.favorite.text = @"0";
        self.bgview.comment.text = @"0";
        self.bgview.forward.text = @"0";
        
        self.bgview.owner.text = self.infomodel.NickName;
        [self.bgview.rotatingImg sd_setImageWithURL:GetUrlWithStr(self.infomodel.UserPictureName)];
        if ([self.infomodel.Sex isEqualToString:@"1"]) {
            self.bgview.seximg.image = GetImgWithStr(@"男");
        } else {
            self.bgview.seximg.image = GetImgWithStr(@"女");
        }
        self.bgview.year.text = self.infomodel.UserGroup;
        
    } else {
        
        self.bgview.titleLB.text = self.model.QuestionText;
        [self.bgview.header sd_setImageWithURL:GetUrlWithStr(self.model.MasterUserPictureName)];
        self.bgview.favorite.text = @"0"; //self.model.LikeCount
        self.bgview.comment.text = @"0"; //self.model.CommentCount
        self.bgview.forward.text = @"0"; //self.model.ShareCount
        
        self.bgview.owner.text = self.infomodel.NickName;
        [self.bgview.rotatingImg sd_setImageWithURL:GetUrlWithStr(self.infomodel.UserPictureName)];
        if ([self.infomodel.Sex isEqualToString:@"1"]) {
            self.bgview.seximg.image = GetImgWithStr(@"男");
        } else {
            self.bgview.seximg.image = GetImgWithStr(@"女");
        }
        self.bgview.year.text = self.infomodel.UserGroup;
    }
    
    if (self.imageJson.length) {
        // 背景图
        NSData *jsondata = [self.imageJson dataUsingEncoding:NSUTF8StringEncoding];
        
        NSArray *imageArr = [NSJSONSerialization JSONObjectWithData:jsondata options:NSJSONReadingAllowFragments | NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:nil];
        
        if (imageArr.count == 1) {
            self.bgview.scrollview.autoScroll = NO;
        } else {
            self.bgview.scrollview.autoScroll = YES;
        }
        
        self.bgview.scrollview.imageURLStringsGroup = imageArr;
    }
    
}

#pragma mark 播放话题
- (void)Hear_PhonographPlayAction:(NSNotification *)sender {
    UIButton *playbtn = sender.object;
    
    if (isRotate == YES) {
        
        [playbtn setImage:GetImgWithStr(@"Phonograph_play") forState:UIControlStateNormal];
        
        [self.player pause];
        
        isRotate = NO;
        
    } else {
        
        [playbtn setImage:GetImgWithStr(@"暂停") forState:UIControlStateNormal];
        
        [self.player play];
        
        isRotate = YES;
        
    }
}

- (void)Hear_PhonographRotatingImgAction:(NSNotification *)sender {
    if (isRotate == YES) {
        [self.bgview.rotatingImg resumeRotate];
    } else {
        [self.bgview.rotatingImg stopRotating];
    }
}

#pragma mark 发布
- (void)sendbtnAction:(UIButton *)sender {
    
    self.sendbtn.enabled = NO;
    
    if (self.topicname.length) {
        // 创建
        [self uploadTopicName];
        
    } else {
        // 回答话题
        if ([self.soundStr containsString:@"mp3"]) {
            [OSSImageUploader asyncUploadSound:@[self.soundStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
                
                if (state == UploadImageFailed) {
                    return;
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self uploadTopicWithSoundName:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] questionID:self.model.QuestionID];
                });
                
            }];
            
        } else {
            [OSSImageUploader asyncUploadOfTypeM4aSound:@[self.soundStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
                if (state == UploadImageFailed) {
                    return;
                }
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self uploadTopicWithSoundName:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] questionID:self.model.QuestionID];
                });
            }];
        }
    }
    
}

// step1
- (void)uploadTopicName {
    NSDictionary *topicParam = @{
                                 @"QuestionText":self.topicname,
                                 @"IsShow":@"1",
                                 @"SortNo":@"0",
                                 @"ParentQuestionID":@"1",
                                 @"CreateTime":[self getCurrentTime],
                                 @"SystemTag":@"其他",
                                 @"SoundCount":@"0",
                                 @"LatestTime":[self getCurrentTime],
                                 @"UserLocalId":USERID,
                                 @"Index":@"0"
                                 };
    
    YTKApi *api = [YTKApi apiPostWithUrl:@"SoundInfo/Post_SaveSoundQuestion" para:topicParam];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                
                NSData *jsonData = [dict[@"BodyContent"] dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                    options:NSJSONReadingMutableContainers
                                                                      error:&err];
                if(err) {
                    NSLog(@"json解析失败：%@",err);
                } else {
                    Hear_TopicShowModel *model = [Hear_TopicShowModel modelWithDictionary:dic];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [self uploadTopicWithID:model.QuestionID];
                    });
                }
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
}

// step2
- (void)uploadTopicWithID:(NSString *)questionID {
    
    if ([self.soundStr containsString:@"mp3"]) {
        [OSSImageUploader asyncUploadSound:@[self.soundStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
            
            if (state == UploadImageFailed) {
                return;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self uploadTopicWithSoundName:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] questionID:questionID];
            });
            
        }];
        
    } else {
        [OSSImageUploader asyncUploadOfTypeM4aSound:@[self.soundStr] complete:^(NSArray<NSString *> *names, UploadImageState state) {
            if (state == UploadImageFailed) {
                return;
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self uploadTopicWithSoundName:[NSString stringWithFormat:@"http://%@.%@%@",BucketName,AliYunHost,[names firstObject]] questionID:questionID];
            });
        }];
    }
    
}

// 上传声音
- (void)uploadTopicWithSoundName:(NSString *)soundstr  questionID:(NSString *)questionID {
    CGFloat sound = [[NSString stringWithFormat:@"%.1f", self.soundLength + 1] floatValue];
    NSDictionary *param = @{
                            @"LocalId":USERID,
                            @"UserLocalId":USERID,
                            @"SoundUrl":soundstr,
                            @"SoundLength":[NSString stringWithFormat:@"%.0f", ceilf(sound)],
                            @"CreateTime":[self getCurrentTime],
                            @"QuestionID":questionID,
                            @"BackGround":self.imageJson.length ? self.imageJson : @""
                            };
    
    YTKApi *api = [YTKApi apiPostWithUrl:@"SoundInfo/Post_SaveSound" para:param];
    [api getSuccessToken:^() {
        api.foceNoTocken = NO;
        [api setRequestSerializerType:YTKRequestSerializerTypeJSON];
        [api startWithCompletionBlockWithSuccess:^(__kindof YTKBaseRequest * _Nonnull request) {
            NSDictionary *dict = request.responseJSONObject;
            
            if ([dict[@"CodeStatus"] integerValue] == 20000) {
                self.sendbtn.enabled = YES;
                
                if (self.topicname.length) {
                    [self showMessage:@"创建成功" atPosition:ShowPosition_Center];
                } else {
                    [self showMessage:@"回复成功" atPosition:ShowPosition_Center];
                }
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            
        } failure:^(__kindof YTKBaseRequest * _Nonnull request) {
            
        }];
    }];
    
}

- (NSString *)getCurrentTime {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
    return [formatter stringFromDate:[NSDate date]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
